package com.ruoyi.tester.controller;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.ruoyi.tester.domain.*;
import com.ruoyi.tester.executor.expression.ExpressionContainer;
import com.ruoyi.tester.service.ITesterInterfaceService;
import com.ruoyi.tester.service.ITesterLoginConfigService;
import com.ruoyi.tester.service.ITesterTaskService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.tester.service.ITesterTaskInterfaceRelationService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 任务-接口关联关系Controller
 *
 * @author ruoyi
 * @date 2022-04-25
 */
@Controller
@RequestMapping("/tester/task_interface_relation")
public class TesterTaskInterfaceRelationController extends BaseController
{
    private String prefix = "tester/task_interface_relation";

    @Autowired
    private ITesterTaskInterfaceRelationService testerTaskInterfaceRelationService;
    @Autowired
    private ITesterTaskService taskService;
    @Autowired
    private ITesterInterfaceService interfaceService;
    @Autowired
    private ITesterLoginConfigService testerLoginConfigService;

    @RequiresPermissions("tester:task_interface_relation:view")
    @GetMapping()
    public String task_interface_relation(ModelMap mmap)
    {
        List<String> expDescList = ExpressionContainer.expressionsDescription();
        String expDesc = expDescList.stream().collect(Collectors.joining("\r\n"));
        mmap.put("expDesc", expDesc);
        List<TesterTask> taskList = taskService.selectTesterTaskList(new TesterTask());
        mmap.put("taskList", taskList);
        List<TesterInterface> interfaceList = interfaceService.selectTesterInterfaceList(new TesterInterface());
        mmap.put("interfaceList", interfaceList);
        return prefix + "/task_interface_relation";
    }

    /**
     * 查询任务-接口关联关系列表
     */
    @ApiOperation("查询任务-接口关联关系列表")
    @RequiresPermissions("tester:task_interface_relation:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TesterTaskInterfaceRelation testerTaskInterfaceRelation)
    {
        List<TesterTask> taskList = taskService.selectTesterTaskList(new TesterTask());
        Map<Long, TesterTask> taskMap = taskList.stream().collect(Collectors.toMap(TesterTask::getTaskId, Function.identity()));
        List<TesterInterface> interfaceList = interfaceService.selectTesterInterfaceList(new TesterInterface());
        Map<Long, TesterInterface> interfaceMap = interfaceList.stream().collect(Collectors.toMap(TesterInterface::getInterfaceId, Function.identity()));
        List<TesterLoginConfig> loginConfigList = testerLoginConfigService.selectAll();
        Map<Long, TesterLoginConfig> loginMap = loginConfigList.stream().collect(Collectors.toMap(TesterLoginConfig::getLoginConfigId, Function.identity()));

        startPage();
        List<TesterTaskInterfaceRelation> list = testerTaskInterfaceRelationService.selectTesterTaskInterfaceRelationList(testerTaskInterfaceRelation);
        TableDataInfo dataTable = getDataTable(list);

        Set<Long> dependRelationIdSet = new HashSet<>();
        for (TesterTaskInterfaceRelation item : list) {
            String dependRelationIds = item.getDependRelationIds();
            if (StringUtils.hasLength(dependRelationIds)) {
                String[] split = dependRelationIds.split(",");
                for (String s : split) {
                    if (StringUtils.hasLength(s.trim())) {
                        dependRelationIdSet.add(Long.valueOf(s.trim()));
                    }
                }
            }
        }
        List<TesterTaskInterfaceRelation> depends = testerTaskInterfaceRelationService.selectInRelationIds(dependRelationIdSet);
        Map<Long, TesterTaskInterfaceRelation> dependMap = depends.stream().collect(Collectors.toMap(TesterTaskInterfaceRelation::getRelationId, Function.identity()));

        List<TesterTaskInterfaceRelationOut> ret = list.stream().map(x -> new TesterTaskInterfaceRelationOut(x, taskMap, interfaceMap, dependMap, loginMap)).collect(Collectors.toList());
        dataTable.setRows(ret);
        return dataTable;
    }

    /**
     * 导出任务-接口关联关系列表
     */
    @RequiresPermissions("tester:task_interface_relation:export")
    @Log(title = "任务-接口关联关系", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TesterTaskInterfaceRelation testerTaskInterfaceRelation)
    {
        List<TesterTaskInterfaceRelation> list = testerTaskInterfaceRelationService.selectTesterTaskInterfaceRelationList(testerTaskInterfaceRelation);
        ExcelUtil<TesterTaskInterfaceRelation> util = new ExcelUtil<TesterTaskInterfaceRelation>(TesterTaskInterfaceRelation.class);
        return util.exportExcel(list, "任务-接口关联关系数据");
    }

    /**
     * 新增任务-接口关联关系
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        List<TesterTask> taskList = taskService.selectTesterTaskList(new TesterTask());
        mmap.put("taskList", taskList);

        List<TesterInterface> interfaceList = interfaceService.selectTesterInterfaceList(new TesterInterface());
        mmap.put("interfaceList", interfaceList);

        List<TesterLoginConfig> loginConfigs = testerLoginConfigService.selectAll();
        mmap.put("loginConfigs", loginConfigs);

        List<String> expDescList = ExpressionContainer.expressionsDescription();
        String expDesc = expDescList.stream().collect(Collectors.joining("\r\n"));
        mmap.put("expDesc", expDesc);

        List<String> expNameList = ExpressionContainer.expressionsName();
        String expNames = expNameList.stream().map(x -> x+"()").collect(Collectors.joining(","));
        mmap.put("expNames", expNames);

        return prefix + "/add";
    }

    /**
     * 新增保存任务-接口关联关系
     */
    @ApiOperation("新增保存任务-接口关联关系")
    @RequiresPermissions("tester:task_interface_relation:add")
    @Log(title = "任务-接口关联关系", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TesterTaskInterfaceRelation testerTaskInterfaceRelation)
    {
        testerTaskInterfaceRelationService.insertTesterTaskInterfaceRelation(testerTaskInterfaceRelation);
        return success(testerTaskInterfaceRelation.getRelationId());
    }

    /**
     * 修改任务-接口关联关系
     */
    @RequiresPermissions("tester:task_interface_relation:edit")
    @GetMapping("/edit/{relationId}")
    public String edit(@PathVariable("relationId") Long relationId, ModelMap mmap)
    {
        TesterTaskInterfaceRelation testerTaskInterfaceRelation = testerTaskInterfaceRelationService.selectTesterTaskInterfaceRelationByRelationId(relationId);
        mmap.put("testerTaskInterfaceRelation", testerTaskInterfaceRelation);

        List<TesterLoginConfig> loginConfigs = testerLoginConfigService.selectAll();
        mmap.put("loginConfigs", loginConfigs);

        List<TesterTask> taskList = taskService.selectTesterTaskList(new TesterTask());
        mmap.put("taskList", taskList);

        List<TesterInterface> interfaceList = interfaceService.selectTesterInterfaceList(new TesterInterface());
        mmap.put("interfaceList", interfaceList);

        TesterTaskInterfaceRelation p = new TesterTaskInterfaceRelation();
        p.setTaskId(testerTaskInterfaceRelation.getTaskId());
        List<TesterTaskInterfaceRelation> relationList = testerTaskInterfaceRelationService.selectTesterTaskInterfaceRelationList(p);
        for (int i=relationList.size()-1; i>=0; i--) {
            TesterTaskInterfaceRelation relation = relationList.get(i);
            //移除自己
            if (relation.getRelationId().equals(relationId)) {
                relationList.remove(i);
                break;
            }
        }
        mmap.put("fullRelationList", relationList);
        if(StringUtils.hasLength(testerTaskInterfaceRelation.getDependRelationIds())) {
            Map<Long, TesterTaskInterfaceRelation> map = relationList.stream().collect(Collectors.toMap(TesterTaskInterfaceRelation::getRelationId, Function.identity()));
            String[] split = testerTaskInterfaceRelation.getDependRelationIds().split(",");
            List<TesterTaskInterfaceRelation> choosedRelationList = Arrays.stream(split).map(x -> map.get(Long.valueOf(x.trim()))).collect(Collectors.toList());
            mmap.put("choosedRelationList", choosedRelationList);
        }

        List<String> expDescList = ExpressionContainer.expressionsDescription();
        String expDesc = expDescList.stream().collect(Collectors.joining("\r\n"));
        mmap.put("expDesc", expDesc);

        List<String> expNameList = ExpressionContainer.expressionsName();
        String expNames = expNameList.stream().map(x -> x+"()").collect(Collectors.joining(","));
        mmap.put("expNames", expNames);
        return prefix + "/edit";
    }

    /**
     * 修改保存任务-接口关联关系
     */
    @ApiOperation("修改保存任务-接口关联关系")
    @RequiresPermissions("tester:task_interface_relation:edit")
    @Log(title = "任务-接口关联关系", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TesterTaskInterfaceRelation testerTaskInterfaceRelation)
    {
        if (testerTaskInterfaceRelation != null && testerTaskInterfaceRelation.getDependRelationIds() == null) {
            testerTaskInterfaceRelation.setDependRelationIds("");
        }
        return toAjax(testerTaskInterfaceRelationService.updateTesterTaskInterfaceRelation(testerTaskInterfaceRelation));
    }

    /**
     * 删除任务-接口关联关系
     */
    @ApiOperation("删除任务-接口关联关系")
    @RequiresPermissions("tester:task_interface_relation:remove")
    @Log(title = "任务-接口关联关系", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(testerTaskInterfaceRelationService.deleteTesterTaskInterfaceRelationByRelationIds(ids));
    }
}
